package cn.rxmind.dlog.common.buffer;

import cn.rxmind.dlog.common.DLogData;
import cn.rxmind.dlog.common.DLogDataBuffer;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @description 
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2020/7/13 2:28 下午
 */
@Slf4j
public class BlockQueueBuffer implements DLogDataBuffer {

    private BlockingQueue<DLogData> buffer ;

    public BlockQueueBuffer(int bufferCapacity) {

        buffer = new LinkedBlockingQueue<>(bufferCapacity);
    }

    @Override
    public boolean add(DLogData logData) {
        return this.buffer.add(logData);
    }

    @Override
    public List<DLogData> batchTake(int num) {
        int min = Math.min(size(), num);
        List<DLogData> result = new LinkedList<>();
        for (int i = 0; i < min; i++) {
            try {
                result.add(this.buffer.take());
            }catch (InterruptedException e){
                log.error("Take LogData Error!",e);
                Thread.currentThread().interrupt();
            }
        }
        return result;
    }

    @Override
    public int size() {
        return this.buffer.size();
    }
}
